<template>
  <layout>
    <!-- 顶部搜索栏 -->
    <div class="header">
      <div class="w">
        <search-input :keyword="keyword" />
      </div>
    </div>
    <div class="bw search">
      <div class="w">
        <!-- 面包屑 -->
        <div class="breadcrumb">
          <el-space wrap>
            <el-link :underline="false" @click="cleanSearchCondition">全部结果</el-link>
            <el-link class="mr1" disabled>></el-link>
            <template v-if="keyword">
              <el-link class="mr1" disabled>"{{ keyword }}"</el-link>
            </template>
            <!-- 分类条件 -->
            <template v-if="category.selectList.length > 0">
              <el-tag 
                v-for="(item, idx) in category.dataList" :key="idx" 
                class="mr2" closable type="info" 
                @close="removeSelectCategoryOrBrandEvent(item, 'cate')">
                <span class="bc-label">分类：</span>
                <span class="bc-value">{{ item.name }}</span>
              </el-tag>
            </template>
            <!-- 品牌条件 -->
            <template v-if="brand.selectList.length > 0">
              <el-tag 
                v-for="(item, idx) in brand.dataList" :key="idx" 
                class="mr2" closable type="info" 
                @close="removeSelectCategoryOrBrandEvent(item, 'brand')">
                <span class="bc-label">品牌：</span>
                <span class="bc-value">{{ item.name }}</span>
              </el-tag>
            </template>
            <!-- 基本属性 -->
            <template v-for="(item, idx) in baseAttr">
              <template 
                v-if="item.hasOwnProperty('selectList') && item['selectList'].length > 0">
                <el-tag :key="idx" class="mr2" closable type="info" 
                  @close="removeSelectAttrEvent(item)">
                  <span class="bc-label">{{ item["name"] }}：</span>
                  <span class="bc-value">{{ item["selectList"].join("、") }}</span>
                </el-tag>
              </template>
            </template>
            <!-- 高级属性 -->
            <template v-for="(item, idx) in advancedAttr">
              <template 
                v-if="item.hasOwnProperty('selectList') && item['selectList'].length > 0">
                <el-tag :key="idx" class="mr2" closable type="info" 
                  @close="removeSelectAttrEvent(item)">
                  <span class="bc-label">{{ item["name"] }}：</span>
                  <span class="bc-value">{{ item["selectList"].join("、") }}</span>
                </el-tag>
              </template>
            </template>
          </el-space>
        </div>
      </div>
      <!-- 选择区域 -->
      <div class="w selector">
        <!-- 分类列表 -->
        <template v-if="category.dataList.length > 0 && category.selectList.length === 0">
          <div class="selector-item">
            <div class="selector-item-title">
              <label>分类：</label>
            </div>
            <div class="selector-item-content">
              <div class="search-cate-box clearfix" :style="category.style">
                <div
                  v-for="(item, idx) in category.dataList"
                  :key="idx"
                  class="fl search-cate-item"
                  @mouseenter.self="mouseenterCategoryEvent"
                  @mouseleave.self="mouseleaveCategoryEvent"
                  @click="selectCategoryEvent($event, item)"
                >
                  <el-link type="primary" :underline="false">
                    {{ item.name }}
                  </el-link>
                </div>
              </div>
            </div>
            <div class="selector-item-ext">
              <el-button-group>
                <template v-if="!category.multiple">
                  <el-button size="small" @click="moreCategoryEvent"> 
                    更多<icon-svg :name="category.arrow"></icon-svg> 
                  </el-button>
                  <el-button size="small" @click="triggerMultipleSelectCategoryEvent"> 
                    <icon-svg name="add-select"></icon-svg>多选 
                  </el-button>
                </template>
                <template v-if="category.multiple">
                  <el-button size="small" @click="cancalMultipleSelectCategoryEvent"> 
                    取消<icon-svg name="close"></icon-svg> 
                  </el-button>
                  <el-button size="small" @click="confirmMultipleSelectCategoryEvent"> 
                    <icon-svg name="seleted"></icon-svg>确定 
                  </el-button>
                </template>
              </el-button-group>
            </div>
          </div>
        </template>
        <!-- 品牌列表 -->
        <template v-if="brand.dataList.length > 0 && brand.selectList.length === 0">
          <div class="selector-item">
            <div class="selector-item-title">
              <label>品牌：</label>
            </div>
            <div class="selector-item-content">
              <div class="search-brand-box clearfix" :style="brand.style">
                <div
                  v-for="(item, idx) in brand.dataList"
                  :key="idx"
                  class="fl search-brand-item"
                  @mouseenter.self="mouseenterBrandEvent"
                  @mouseleave.self="mouseleaveBrandEvent"
                  @click="selectBrandEvent($event, item)"
                >
                  <el-image :src="item.logo" fit="fill" />
                  <div class="brand-desc">{{ item.name }}</div>
                </div>
              </div>
            </div>
            <div class="selector-item-ext">
              <el-button-group>
                <template v-if="!brand.multiple">
                  <el-button size="small" @click="moreBrandEvent"> 
                    更多<icon-svg :name="brand.arrow"></icon-svg> 
                  </el-button>
                  <el-button size="small" @click="triggerMultipleSelectBrandEvent"> 
                    <icon-svg name="add-select"></icon-svg>多选 
                  </el-button>
                </template>
                <template v-if="brand.multiple">
                  <el-button size="small" @click="cancalMultipleSelectBrandEvent"> 
                    取消<icon-svg name="close"></icon-svg> 
                  </el-button>
                  <el-button size="small" @click="confirmMultipleSelectBrandEvent"> 
                    <icon-svg name="seleted"></icon-svg>确定 
                  </el-button>
                </template>
              </el-button-group>
            </div>
          </div>
        </template>
        <!-- 商品属性列表 -->
        <template v-if="baseAttr.dataList.length > 0">
          <template v-for="(item, idx) in baseAttr.dataList">
            <div :key="idx" v-if="item.values.length > 0 && baseAttr[item.id].selectList.length === 0" class="selector-item">
              <div class="selector-item-title">
                <label>{{ item.name }}：</label>
              </div>
              <div class="selector-item-content">
                <div class="search-attr-box clearfix" :style="baseAttr[item.id].style">
                  <div
                    v-for="(value, iidx) in item.values"
                    :key="iidx"
                    class="fl search-attr-item"
                    @mouseenter.self="mouseenterBaseAttrEvent"
                    @mouseleave.self="mouseleaveBaseAttrEvent"
                    @click="selectBaseAttrEvent($event, item, value)"
                  >
                    <el-link type="primary" :underline="false">
                      {{ value }}
                    </el-link>
                  </div>
                </div>
              </div>
              <div class="selector-item-ext">
                <el-button-group>
                  <template v-if="!baseAttr[item.id].multiple">
                    <el-button size="small" @click="moreBaseAttrEvent(item)"> 
                      更多<icon-svg :name="baseAttr[item.id].arrow"></icon-svg> 
                    </el-button>
                    <el-button size="small" @click="triggerMultipleSelectBaseAttrEvent(item)"> 
                      <icon-svg name="add-select"></icon-svg>多选 
                    </el-button>
                  </template>
                  <template v-if="baseAttr[item.id].multiple">
                    <el-button size="small" @click="cancalMultipleSelectBaseAttrEvent(item)"> 
                      取消<icon-svg name="close"></icon-svg> 
                    </el-button>
                    <el-button size="small" @click="confirmMultipleSelectBaseAttrEvent(item)"> 
                      <icon-svg name="seleted"></icon-svg>确定 
                    </el-button>
                  </template>
                </el-button-group>
              </div>
            </div>
          </template>
        </template>
        <!-- 高级属性选项 -->
        <template v-if="advancedAttr.dataList.length > 0 && advancedAttr.visible">
          <div class="selector-item">
            <div class="selector-item-title">
              <label>高级选项：</label>
            </div>
            <div class="selector-item-content">
              <div class="search-advanced-attr-box clearfix">
                <template v-for="(item, idx) in advancedAttr.dataList">
                  <template v-if="item.values.length > 0 && advancedAttr[item.id].selectList.length === 0">
                    <div :key="idx" class="fl search-advanced-attr-item">
                      <el-popover popper-class="search-advanced-attr-popover" placement="bottom-start" :hide-after="500" trigger="hover">
                        <template #reference>
                          <el-link type="primary" :underline="false">
                            {{ item.name }}
                          </el-link>
                        </template>
                        <div class="search-advanced-attr-item">
                          <div class="search-advanced-attr-content clearfix">
                            <div
                              v-for="(value, iidx) in item.values"
                              :key="iidx"
                              class="search-advanced-attr-item fl"
                              @mouseenter.self="mouseenterAdvancedAttrEvent"
                              @mouseleave.self="mouseleaveAdvancedAttrEvent"
                              @click="selectAdvancedAttrEvent($event, item, value)"
                            >
                              <el-link type="primary" :underline="false">
                                {{ value }}
                              </el-link>
                            </div>
                          </div>
                          <div class="search-advanced-attr-ext">
                            <el-button-group>
                              <template v-if="!advancedAttr[item.id].multiple">
                                <el-button size="small" @click="closeSelectAdvancedAttrEvent(item)"> <icon-svg name="close"></icon-svg>关闭 </el-button>
                                <el-button size="small" @click="triggerMultipleSelectAdvancedAttrEvent(item)"> <icon-svg name="add-select"></icon-svg>多选 </el-button>
                              </template>
                              <template v-if="advancedAttr[item.id].multiple">
                                <el-button size="small" @click="cancalMultipleSelectAdvancedAttrEvent(item)"> 取消<icon-svg name="close"></icon-svg> </el-button>
                                <el-button size="small" @click="confirmMultipleSelectAdvancedAttrEvent(item)"> <icon-svg name="seleted"></icon-svg>确定 </el-button>
                              </template>
                            </el-button-group>
                          </div>
                        </div>
                      </el-popover>
                    </div>
                  </template>
                </template>
              </div>
            </div>
          </div>
        </template>
      </div>
      <!-- 搜索结果区域 -->
      <div class="w pad-20-0">
        <!-- 排序、分页 -->
        <div class="search-top">
          <el-row>
            <el-col :span="8">
              <el-button-group>
                <el-button 
                  :type="sort.field === '' ? 'danger' : ''" 
                  size="small" @click="triggerSortEvent('')"> 
                  综合<icon-svg name="falling"></icon-svg> 
                </el-button>
                <el-button 
                  :type="sort.field === 'sales' ? 'danger' : ''" 
                  size="small" @click="triggerSortEvent('sales')">
                  销量<icon-svg name="falling"></icon-svg>
                </el-button>
                <el-button size="small" @click="triggerSortEvent('comment')"> 
                  评论数<icon-svg name="falling"></icon-svg> 
                </el-button>
                <el-button size="small" @click="triggerSortEvent('news')"> 
                  新品<icon-svg name="falling"></icon-svg> 
                </el-button>
                <el-button 
                  :type="sort.field === 'price' ? 'danger' : ''" 
                  size="small" @click="triggerSortEvent('price')"> 
                  价格<icon-svg :name="sort.field != 'price' ? 'sorting' : (sort.order === 'asc' ? 'rising' : 'falling')"></icon-svg> 
                </el-button>
              </el-button-group>
            </el-col>
            <el-col :span="6">
              <div style="width: 180px">
                <el-row>
                  <el-col :span="11">
                    <el-input 
                      v-model="price.min" size="small" placeholder="¥" 
                      :formatter="(value) => `$ ${value}`.replace(/[^\d]*/g, '')"
                      @change="changePriceEvent" />
                  </el-col>
                  <el-col class="line" :span="2" style="text-align: center; vertical-align: middle">
                    <span>-</span>
                  </el-col>
                  <el-col :span="11">
                    <el-input 
                      v-model="price.max" size="small" placeholder="¥" 
                      :formatter="(value) => `$ ${value}`.replace(/[^\d]*/g, '')"
                      @change="changePriceEvent" />
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="fr">
                <span>共{{ total }}件商品</span>
                <span>
                  &nbsp;&nbsp;{{ current }}
                  /
                  {{ pages }}&nbsp;&nbsp;
                </span>
                <el-button-group>
                  <el-button 
                    size="small" 
                    :disabled="(current === 1)"
                    @click="toPage('pre')">
                    <icon-svg name="arrow-left"></icon-svg>
                  </el-button>
                  <el-button 
                    size="small"
                    :disabled="(current === pages)"
                    @click="toPage('next')">
                    <icon-svg name="arrow-right"></icon-svg>
                  </el-button>
                </el-button-group>
              </div>
            </el-col>
          </el-row>
        </div>
        <!-- 商品列表 -->
        <div class="search-content pad-10-0 clearfix">
          <div v-for="(sku, idx) in skuList" :key="idx" :span="4" class="sku-item fl">
            <el-card :style="{ border: '0px' }" :body-style="{ padding: '0px' }" shadow="hover">
              <div class="p-img">
                <router-link target="_blank" :to="`/item/${sku.id}`">
                  <el-image :src="sku.defaultImage" fit="fill" lazy></el-image>
                </router-link>
              </div>
              <div class="p-scroll clearfix">
                <div class="p-main">
                  <span 
                    v-if="(sku.images.length > 6)" class="m-pre"
                    @click.stop="clickSkuPicItemPreEvent">
                    <icon-svg name="arrow-left" :size="1.5"></icon-svg>
                  </span>
                  <div :style="sku.images.length <= 6 ? 'width: 100%;left: 0px;' : ''" class="m-wrap">
                    <el-space :size="3" style="position: relative;">
                      <div 
                        v-for="(image, iidx) in sku.images" :key="iidx" 
                        :class="('m-item fl' + (sku.defaultImage === image.url ? ' m-item_select' : ''))"
                        @mouseenter.self="mouseenterSkuPicItemEvent($event, sku, image)">
                        <el-image :src="image.url" fit="fill" lazy></el-image>
                      </div>
                    </el-space>
                  </div>
                  <span 
                    v-if="(sku.images.length > 6)" class="m-next"
                    @click.stop="clickSkuPicItemNextEvent">
                    <icon-svg name="arrow-right" :size="1.5"></icon-svg>
                  </span>
                </div>
              </div>
              <div class="p-price">
                <strong>
                  <em>￥</em>
                  <i>{{ sku.price }}</i>
                </strong>
              </div>
              <div class="p-title">
                <router-link target="_blank" :to="`/item/${sku.id}`">
                  <em v-html="sku.title"></em>
                </router-link>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </layout>
</template>

<script lang="ts" setup>
import merge from "lodash/merge";
import { useRouter } from "vue-router";
import http from "@/utils/httpRequest.js";
import { ref, watch, reactive, onBeforeMount, onMounted } from "vue";
import { addElementClassName, removeElementClassName } from "@/utils";

import "@/assets/scss/modules/search.scss";
import SearchInput from "@/views/commons/search-input.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Layout from "@/views/commons/layout/index.vue";

const router = useRouter();

// 关键字
const keyword = ref('');

// 当前页码
const current = ref(1);

// 一共多少条数据
const total = ref(0);

// 每页多少条数据
const size = ref(50);

// 一共多少页
const pages = ref(0);

// 检索商品列表
const skuList = ref([]);

// 分类相关数据
const category = reactive({
  // 检索返回的数据
  dataList: [],
  // 是否多选标志
  multiple: false,
  // 选中的集合
  selectList: [],
  // 临时选中集合，多选时用到
  tempSelectList: [],
  // 更多事件相关属性
  more: false,
  style: {
    height: "auto",
    overflow: "hidden",
    "max-height": "50px",
  },
  arrow: "arrow-down",
});

// 品牌相关数据
const brand = reactive({
  // 检索返回的数据
  dataList: [],
  // 是否多选标志
  multiple: false,
  // 选中的集合
  selectList: [],
  // 临时选中集合，多选时用到
  tempSelectList: [],
  // 更多事件相关属性
  more: false,
  style: {
    height: "50px",
    overflow: "hidden",
    "min-height": "50px",
    "max-height": "100px",
  },
  arrow: "arrow-down",
});

// 基础属性相关数据
const baseAttr = reactive({
  // 检索返回的数据
  dataList: [],
});

// 高级属性相关数据
const advancedAttr = reactive({
  // 检索返回的数据
  dataList: [],
  // 高级属性是否显示
  visible: false,
});

// 监听高级属性是否需要显示
watch(
  advancedAttr,
  (val) => {
    for (const key in val) {
      let o = val[key];
      if (o.hasOwnProperty("selectList") && o["selectList"].length === 0) {
        advancedAttr.visible = true;
        return;
      }
    }
    advancedAttr.visible = false;
  },
  { immediate: true, deep: true }
);

// 排序
const sort = reactive({
  field: "",
  order: "",
});

// 价格区间
const price = reactive({
  min: '',
  max: '',
});

// 组件被挂载之前被调用
onBeforeMount(() => {
  // 检索关键字初始化
  keyword.value = obtainParamByRoute('keyword');
  // 排序初始化
  let sortString = obtainParamByRoute('sort');
  if (sortString) {
    let ss = sortString.split('_');
    sort.field = ss[0];
    sort.order = ss.length > 1 ? ss[1] : 'asc';
  }
  // 价格范围初始化
  let priceString = obtainParamByRoute('price');
  if (priceString) {
    let ss = priceString.split('_');
    price.min = ss[0];
    price.max = ss.length > 1 ? ss[1] : '';
  }
  // 分页相关
  let currentString = obtainParamByRoute('current');
  if (currentString) {
    current.value = parseInt(currentString);
  }
});

// 组件挂载完成后执行
onMounted(() => {
  // 查询商品信息
  loadSkuData();
});

// 加载 sku 数据（重新检索）
const loadSkuData = () => {
  let params = obtainParamsByRoute();
  params['current'] = current.value + '';
  params['size'] = size.value + '';
  http
    .post({
      url: "/search/sku/select",
      data: params,
    })
    .then(({ data }) => {
      if (http.success(data, false)) {
        const body = data.body;
        // 商品信息
        handleSkusSearchResult(body.skus);
        // 商品属性信息
        handleAttrsSearchResult(body.attrs);
        // 分类信息
        handleCategorySearchResult(body.categorys);
        // 商品品牌信息
        handleBrandSearchResult(body.brands);
        // 分页信息
        current.value = body.current;
        total.value = body.total;
        pages.value = body.pages;
      }
    });
};

// 处理商品信息
const handleSkusSearchResult = (skus) => {
  for (let i = 0; i < skus.length; i++) {
    let sku = skus[i];
    let images = sku.images;
    // 没有图片，默认赋值
    if (!images || images.length === 0) {
      let invalid = "/images/invalid.jpeg";
      sku.images = [{ url: invalid }];
      sku.defaultImage = invalid;
      continue;
    }
    // 提取默认图片
    let defaultImage = images.filter(item => item.default === true);
    sku["defaultImage"] = defaultImage.length > 0 ? defaultImage[0].url : images[0]["url"];
  }
  skuList.value = skus;
};

// 处理商品属性信息
const handleAttrsSearchResult = (attrs) => {
  // 如果属性个数少于5个则不处理
  if (attrs.length <= 4) {
    baseAttr.dataList = attrs;
  }
  // 如果属性个数大于4个则分为基本属性和高级属性
  else {
    baseAttr.dataList = attrs.slice(0, 4);
    advancedAttr.dataList = attrs.slice(4);
  }
  // 初始化基础商品属性附加数据
  initBaseAttrsData();
  // 初始化高级商品属性附加数据
  initAdvanceAttrsData();
  // 初始化选中数据
  initAttrSelectData();
};

// 初始化选中的属性
const initAttrSelectData = () => {
  // 格式：attrId11_value11||value12^attrId21_value21||value22
  let attrs = obtainParamByRoute('attrs');
  // 初始化默认选中属性
  attrs.split('^')
    .forEach(attr => {
      let ao = attr.split('_');
      if (!ao || ao.length < 2) {
        return;
      }
      let attrId = ao[0];
      let attrValues = ao[1].split('||');
      if (baseAttr.hasOwnProperty(attrId)) {
        attrValues.forEach(item => baseAttr[attrId].selectList.push(item));
        return;
      }
      if (advancedAttr.hasOwnProperty(attrId)) {
        attrValues.forEach(item => advancedAttr[attrId].selectList.push(item));
        return;
      }
    });
  // 如果属性值只有一个，则默认选中
  // for (let i = 0; i < baseAttr.dataList.length; i++) {
  //   const attr = baseAttr.dataList[i];
  //   if (attr.values.length === 1 || baseAttr[attr.id]['selectList'].length === 0) {
  //     baseAttr[attr.id]['selectList'].push(attr.values[0]);
  //   }
  // }
  // for (let i = 0; i < advancedAttr.dataList.length; i++) {
  //   const attr = advancedAttr.dataList[i];
  //   if (attr.values.length === 1 || advancedAttr[attr.id]['selectList'].length === 0) {
  //     advancedAttr[attr.id]['selectList'].push(attr.values[0]);
  //   }
  // }
};

// 初始化基础商品属性附加数据
const initBaseAttrsData = () => {
  let dataList = baseAttr.dataList;
  for (let i = 0; i < dataList.length; i++) {
    let attr = dataList[i];
    baseAttr[attr.id] = {
      id: attr.id,
      name: attr.name,
      // 是否多选标志
      multiple: false,
      // 选中的集合
      selectList: [],
      // 临时选中集合，多选时用到
      tempSelectList: [],
      // 更多事件相关属性
      more: false,
      style: {
        height: "auto",
        overflow: "hidden",
        "max-height": "50px",
      },
      arrow: "arrow-down",
    };
  }
};

// 初始化高级商品属性附加数据
const initAdvanceAttrsData = () => {
  let dataList = advancedAttr.dataList;
  for (let i = 0; i < dataList.length; i++) {
    let attr = dataList[i];
    advancedAttr[attr.id] = {
      id: attr.id,
      name: attr.name,
      // 是否多选标志
      multiple: false,
      // 选中的集合
      selectList: [],
      // 临时选中集合，多选时用到
      tempSelectList: [],
    };
  }
};

// 处理分类查询结果
const handleCategorySearchResult = (categorys) => {
  // 初始化查询结果
  category.dataList = categorys;
  // 初始化选中数据
  let cateIds = obtainParamByRoute('cate');
  cateIds.split(',')
    .forEach(cateId => {
      category.dataList
        .filter(item => item.id === cateId)
        .forEach(item => category.selectList.push(item));
    });
  // 如果只命中一个分类，则默认选中
  // if (category.dataList.length == 1 && category.selectList.length == 0) {
  //   category.selectList.push(category.dataList[0]);
  // }
};

// 处理品牌查询结果
const handleBrandSearchResult = (brands) => {
  // 初始化查询结果
  brand.dataList = brands;
  // 初始化选中数据
  let brandIds = obtainParamByRoute('brand');
  brandIds.split(',')
    .forEach(brandId => {
      brand.dataList
        .filter(item => item.id === brandId)
        .forEach(item => brand.selectList.push(item));
    });
  // 如果只命中一个品牌，则默认选中
  // if (brand.dataList.length == 1 && brand.selectList.length == 0) {
  //   brand.selectList.push(brand.dataList[0]);
  // }
};

// 选中分类处理
const selectCategoryHandle = () => {
  if (category.selectList.length === 0) {
    return;
  }
  let cateIds = [];
  let cateIdString = obtainParamByRoute('cate');
  if (cateIdString) {
    cateIds = cateIds.concat(cateIdString.split(','));
  }
  cateIds = cateIds.concat(category.selectList.map(item => item.id));
  let query = router.currentRoute.value.query;
  query['cate'] = cateIds.join(',');
  router.push({ name: "redirect-search", query: query, });
};

// 分类选中事件
const selectCategoryEvent = (event, item) => {
  // 多选处理
  if (category.multiple) {
    let idx = category.tempSelectList.indexOf(item);
    if (idx === -1) {
      addElementClassName(event.currentTarget, "cate_selected");
      category.tempSelectList.push(item);
      return;
    }
    removeElementClassName(event.currentTarget, "cate_selected");
    category.tempSelectList.splice(idx, 1);
    return;
  }
  // 单选处理
  let idx = category.selectList.indexOf(item);
  idx === -1 ? category.selectList.push(item) : category.selectList.splice(idx, 1);
  selectCategoryHandle();
};

// 分类鼠标移上事件
const mouseenterCategoryEvent = (event) => {
  addElementClassName(event.currentTarget, "cate_hover");
};

// 分类鼠标移出事件
const mouseleaveCategoryEvent = (event) => {
  removeElementClassName(event.currentTarget, "cate_hover");
};

// 分类更多按钮点击事件
const moreCategoryEvent = () => {
  if (!category.more) {
    category.style.height = "auto";
    category.style.overflow = "auto";
    category.style["max-height"] = "52px";
    category.arrow = "arrow-up";
  } else {
    category.style.height = "26px";
    category.style.overflow = "hidden";
    category.style["max-height"] = "26px";
    category.arrow = "arrow-down";
  }
  category.more = !category.more;
};

// 触发分类多选事件
const triggerMultipleSelectCategoryEvent = () => {
  moreCategoryEvent();
  category.multiple = true;
  category.tempSelectList = [];
};

// 取消分类多选事件
const cancalMultipleSelectCategoryEvent = () => {
  category.multiple = false;
  category.tempSelectList = [];
};

// 确认分类多选事件
const confirmMultipleSelectCategoryEvent = () => {
  category.multiple = false;
  category.selectList = category.tempSelectList;
  category.tempSelectList = [];
  selectCategoryHandle();
};

// 选中品牌处理
const selectBrandHandle = () => {
  if (brand.selectList.length === 0) {
    return;
  }
  let brandIds = [];
  let brandIdsString = obtainParamByRoute('brand');
  if (brandIdsString) {
    brandIds = brandIds.concat(brandIdsString.split(','));
  }
  brandIds = brandIds.concat(brand.selectList.map(item => item.id));
  let query = router.currentRoute.value.query;
  query['brand'] = brandIds.join(',');
  router.push({ name: "redirect-search", query: query, });
};

// 品牌选中事件
const selectBrandEvent = (event, item) => {
  // 多选处理
  if (brand.multiple) {
    let idx = brand.tempSelectList.indexOf(item);
    if (idx === -1) {
      addElementClassName(event.currentTarget, "brand_selected");
      brand.tempSelectList.push(item);
      return;
    }
    removeElementClassName(event.currentTarget, "brand_selected");
    brand.tempSelectList.splice(idx, 1);
    return;
  }
  // 单选处理
  let idx = brand.selectList.indexOf(item);
  idx === -1 ? brand.selectList.push(item) : brand.selectList.splice(idx, 1);
  selectBrandHandle();
};

// 品牌鼠标移上事件
const mouseenterBrandEvent = (event) => {
  addElementClassName(event.currentTarget, "brand_hover");
};

// 品牌鼠标移出事件
const mouseleaveBrandEvent = (event) => {
  removeElementClassName(event.currentTarget, "brand_hover");
};

// 商品品牌更多按钮点击事件
const moreBrandEvent = () => {
  if (!brand.more) {
    brand.style.height = "auto";
    brand.style.overflow = "auto";
    brand.style["min-height"] = "50px";
    brand.style["max-height"] = "100px";
    brand.arrow = "arrow-up";
  } else {
    brand.style.height = "50px";
    brand.style.overflow = "hidden";
    brand.arrow = "arrow-down";
  }
  brand.more = !brand.more;
};

// 触发品牌多选事件
const triggerMultipleSelectBrandEvent = () => {
  moreBrandEvent();
  brand.multiple = true;
  brand.tempSelectList = [];
};

// 取消品牌多选事件
const cancalMultipleSelectBrandEvent = () => {
  brand.multiple = false;
  brand.tempSelectList = [];
};

// 确认品牌多选事件
const confirmMultipleSelectBrandEvent = () => {
  brand.multiple = false;
  brand.selectList = brand.tempSelectList;
  brand.tempSelectList = [];
  selectBrandHandle();
};

// 选中品牌处理
const selectAttrHandle = () => {
  let selectList = mergeSelectAttrs();
  if (selectList.length === 0) {
    return;
  }
  let attrs = [];
  let attrIds = [];
  let attrsString = obtainParamByRoute('attrs');
  if (attrsString) {
    attrsString
      .split('^')
      .forEach(item => {
        attrIds.push(item.split('_')[0]);
        attrs.push(item);
      });
  }
  selectList
    .filter(item => attrIds.indexOf(item.id) === -1)
    .forEach(item => {
      attrs.push(item.id + '_' + item.selectList.join('||'));
    });
  let query = router.currentRoute.value.query;
  query['attrs'] = attrs.join('^');
  router.push({ name: "redirect-search", query: query, });
};

// 基本属性选中事件
const selectBaseAttrEvent = (event, item, value) => {
  let attr = baseAttr[item.id];
  // 多选处理
  if (attr.multiple) {
    let idx = attr.tempSelectList.indexOf(value);
    if (idx === -1) {
      addElementClassName(event.currentTarget, "base-attr_selected");
      attr.tempSelectList.push(value);
      return;
    }
    removeElementClassName(event.currentTarget, "base-attr_selected");
    attr.tempSelectList.splice(idx, 1);
    return;
  }
  // 单选处理
  let idx = attr.selectList.indexOf(value);
  idx === -1 ? attr.selectList.push(value) : attr.selectList.splice(idx, 1);
  selectAttrHandle();
};

// 基本属性鼠标移上事件
const mouseenterBaseAttrEvent = (event) => {
  addElementClassName(event.currentTarget, "base-attr_hover");
};

// 基本属性鼠标移出事件
const mouseleaveBaseAttrEvent = (event) => {
  removeElementClassName(event.currentTarget, "base-attr_hover");
};

// 基本属性更多按钮点击事件
const moreBaseAttrEvent = (item) => {
  let attr = baseAttr[item.id];
  if (!attr.more) {
    attr.style.height = "auto";
    attr.style.overflow = "auto";
    attr.style["max-height"] = "52px";
    attr.arrow = "arrow-up";
  } else {
    attr.style.height = "26px";
    attr.style.overflow = "hidden";
    attr.style["max-height"] = "26px";
    attr.arrow = "arrow-down";
  }
  attr.more = !attr.more;
};

// 触发基本属性多选事件
const triggerMultipleSelectBaseAttrEvent = (item) => {
  let attr = baseAttr[item.id];
  moreBaseAttrEvent(item);
  attr.multiple = true;
  attr.tempSelectList = [];
};

// 取消基本属性多选事件
const cancalMultipleSelectBaseAttrEvent = (item) => {
  let attr = baseAttr[item.id];
  attr.multiple = false;
  attr.tempSelectList = [];
};

// 确认基本属性多选事件
const confirmMultipleSelectBaseAttrEvent = (item) => {
  let attr = baseAttr[item.id];
  attr.multiple = false;
  attr.selectList = attr.tempSelectList;
  attr.tempSelectList = [];
  selectAttrHandle();
};

// 高级属性选中事件
const selectAdvancedAttrEvent = (event, item, value) => {
  let attr = advancedAttr[item.id];
  // 多选处理
  if (attr.multiple) {
    let idx = attr.tempSelectList.indexOf(value);
    if (idx === -1) {
      addElementClassName(event.currentTarget, "advanced-attr_selected");
      attr.tempSelectList.push(value);
      return;
    }
    removeElementClassName(event.currentTarget, "advanced-attr_selected");
    attr.tempSelectList.splice(idx, 1);
    return;
  }
  // 单选处理
  let idx = attr.selectList.indexOf(value);
  idx === -1 ? attr.selectList.push(value) : attr.selectList.splice(idx, 1);
  selectAttrHandle();
};

// 高级属性鼠标移上事件
const mouseenterAdvancedAttrEvent = (event) => {
  addElementClassName(event.currentTarget, "advanced-attr_hover");
};

// 高级属性鼠标移出事件
const mouseleaveAdvancedAttrEvent = (event) => {
  removeElementClassName(event.currentTarget, "advanced-attr_hover");
};

// 关闭高级属性浮窗
const closeSelectAdvancedAttrEvent = (item) => {
  let attr = advancedAttr[item.id];
  attr.visible = false;
};

// 触发高级属性多选事件
const triggerMultipleSelectAdvancedAttrEvent = (item) => {
  let attr = advancedAttr[item.id];
  attr.multiple = true;
  attr.tempSelectList = [];
};

// 取消高级属性多选事件
const cancalMultipleSelectAdvancedAttrEvent = (item) => {
  let attr = advancedAttr[item.id];
  attr.multiple = false;
  attr.tempSelectList = [];
};

// 确认高级属性多选事件
const confirmMultipleSelectAdvancedAttrEvent = (item) => {
  let attr = advancedAttr[item.id];
  attr.multiple = false;
  attr.selectList = attr.tempSelectList;
  attr.tempSelectList = [];
  selectAttrHandle();
};

// 触发排序事件
const triggerSortEvent = (field) => {
  if (field === 'news' || field === 'comment') {
    ElMessage.warning('功能暂未实现！');
    return;
  }
  let query = router.currentRoute.value.query;
  if (!field) {
    delete query['sort'];
  } else {
    let order = field === 'price' ? (sort.order === 'asc' ? 'desc' : 'asc') : 'asc';
    query['sort'] = field + '_' + order;
  }
  router.push({ name: "redirect-search", query: query, });
};

// 价格范围查询
const changePriceEvent = () => {
  let query = router.currentRoute.value.query;
  if (!price.min && !price.max) {
    delete query['price'];
  } else {
    query['price'] = price.min + '_' + price.max;
  }
  router.push({ name: "redirect-search", query: query, });
};

// 合并选中的属性
const mergeSelectAttrs = () => {
  let attrs = [];
  for (const key in baseAttr) {
    let attr = baseAttr[key];
    if (Object.prototype.hasOwnProperty.call(attr, 'selectList') && attr['selectList'].length > 0) {
      attrs.push(attr);
    }
  }
  for (const key in advancedAttr) {
    let attr = advancedAttr[key];
    if (Object.prototype.hasOwnProperty.call(attr, 'selectList') && attr['selectList'].length > 0) {
      attrs.push(attr);
    }
  }
  return attrs;
}

// 移除选中的分类条件
const removeSelectCategoryOrBrandEvent = (item, name) => {
  let itemIds = obtainParamByRoute(name);
  let cateString = itemIds.split(',').filter(itemId => itemId !== item.id).join(',');
  let query = router.currentRoute.value.query;
  cateString ? (query[name] = cateString) : (delete query[name]);
  router.push({ name: "redirect-search", query: query, });
};

// 移除选中的基本属性条件
const removeSelectAttrEvent = (item) => {
  let attrs = obtainParamByRoute('attrs');
  let attrsString = attrs.split('^')
    .filter(attr => {
      let ao = attr.split('_');
      return ao && ao.length >= 2 && ao[0] !== item.id;
    })
    .join('^');
  let query = router.currentRoute.value.query;
  attrsString ? (query['attrs'] = attrsString) : (delete query['attrs']);
  router.push({ name: "redirect-search", query: query, });
};

// 缩略图向前
const clickSkuPicItemPreEvent = (event) => {
  let pre = event.currentTarget;
  let wrap = pre.nextElementSibling;
  let box = wrap.firstChild;
  let left = (box.offsetLeft - 37);
  if (left + box.offsetWidth <= wrap.offsetWidth) {
    return;
  }
  box.style.left = left + 'px';
};

// 缩略图向后
const clickSkuPicItemNextEvent = (event) => {
  let next = event.currentTarget;
  let wrap = next.previousElementSibling;
  let box = wrap.firstChild;
  let left = (box.offsetLeft + 37);
  if (left > 0) {
    return;
  }
  box.style.left = left + 'px';
};

// 缩略图鼠标移上
const mouseenterSkuPicItemEvent = (event, sku, image) => {
  sku['defaultImage'] = image.url;
};

// 跳转页码
const toPage = (type) => {
  let query = router.currentRoute.value.query;
  if ((type === 'pre' && current.value <= 1) || (type === 'next' && current.value >= pages.value)) {
    return;
  }
  query['current'] = (type === 'pre' ? (current.value - 1) : (current.value + 1)) + '';
  router.push({ name: "redirect-search", query: query, });
};

// 清除查询条件（显示全部）
const cleanSearchCondition = () => {
  router.push({
    name: "redirect-search",
    query: { keyword: keyword.value, },
  });
};

// 移除路由中指定的参数
const deleteParamByRoute = (name) => {
  let query = router.currentRoute.value.query;
  if (query.hasOwnProperty(name)) {
    delete query[name];
  }
  router.push({
    name: "search",
    query: query,
  });
};

// 获取路由中指定的参数
const obtainParamByRoute = (name) => {
  let query = router.currentRoute.value.query;
  return query[name] ? query[name] + '' : '';
};

// 获取路由中全部参数
const obtainParamsByRoute = () => {
  return merge({}, router.currentRoute.value.query);
};
</script>
